import 'dart:io';

import 'package:aero_frisbee/app/store/app_store.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get_it/get_it.dart';
import 'package:package_info_plus/package_info_plus.dart';

class HeaderInterceptor extends Interceptor {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final appStore = GetIt.I.get<AppStore>();

    if (options.path != 'security/oauth') {
      final String accessToken = appStore.token;
      if (accessToken.isNotEmpty) {
        options.headers['Authorization'] = 'Bearer$accessToken';
      }
    }
    final deviceInfo = DeviceInfoPlugin();
    final packageInfo = await PackageInfo.fromPlatform();

    options.headers['device-id'] = await FlutterUdid.udid;
    options.headers['pkg'] = packageInfo.packageName;
    options.headers['ver'] = packageInfo.version;
    options.headers['p_ver'] = packageInfo.buildNumber;
    if (Platform.isIOS) {
      options.headers['platform'] = 'iOS';
      final iosInfo = await deviceInfo.iosInfo;
      options.headers['model'] = iosInfo.utsname.machine;
    } else {
      options.headers['platform'] = 'Android';
      final androidInfo = await deviceInfo.androidInfo;
      options.headers['model'] = androidInfo.model; // 设备型号
    }
    options.headers['kst'] = '1';
    options.headers['sys_lan'] = appStore.languageCode; // 手机系统语言 如英文en 中文zh
    options.headers['lang'] = appStore.languageCode; // 手机系统语言 如英文en 中文zh
    handler.next(options);
  }
}
